<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;
use Sales\Entity\OrderGoods;
use Sales\Entity\OrderGoodsReturn;
use Sales\Form\OrderGoodsReturnForm;
use Sales\Form\SearchOrderGoodsReturnForm;
use Sales\Service\OrderGoodsReturnManager;
use User\Entity\User;
use User\Service\BalanceLogManager;
use User\Service\UserManager;

class SalesServiceController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $orderGoodsReturnManager;
    private $balanceLogManager;
    private $userManager;

    public function __construct(
        Translator      $translator,
        EntityManager   $entityManager,
        OrderGoodsReturnManager $orderGoodsReturnManager,
        BalanceLogManager $balanceLogManager,
        UserManager     $userManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->orderGoodsReturnManager = $orderGoodsReturnManager;
        $this->balanceLogManager= $balanceLogManager;
        $this->userManager      = $userManager;
    }

    /**
     * 退换货列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $page = (int) $this->params()->fromQuery('page', 1);

        $search = [];
        $searchForm = new SearchOrderGoodsReturnForm();
        $searchForm->get('return_type')->setValueOptions(Common::orderGoodsReturnType($this->translator));
        $searchForm->get('return_state')->setValueOptions(Common::orderGoodsReturnState($this->translator));
        if($this->getRequest()->isGet()) {
            $data = $this->params()->fromQuery();
            $searchForm->setData($data);
            if($searchForm->isValid()) $search = $searchForm->getData();
        }

        $query      = $this->entityManager->getRepository(OrderGoodsReturn::class)->findOrderReturnList($search);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return ['goodsReturnList' => $paginator, 'searchForm' => $searchForm];
    }

    /**
     * 审核退换货信息
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $returnId = (int) $this->params()->fromRoute('id', -1);
        $returnInfo = $this->entityManager->getRepository(OrderGoodsReturn::class)->findOneBy(['returnId' => $returnId, 'returnState' => 1]);
        if ($returnInfo == null) return $this->adminCommon()->toReferer();

        $orderGoodsInfo = $this->entityManager->getRepository(OrderGoods::class)->findOrderGoodsAndOrder($returnInfo->getOrderGoodsId());

        $queryData = $this->params()->fromQuery();

        $form = new OrderGoodsReturnForm();
        $form->get('returnState')->setValueOptions(Common::orderGoodsReturnState($this->translator));

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();
                if ($data['returnState'] == 1) return $this->redirect()->toRoute('sales-service');

                $this->entityManager->beginTransaction();
                try {
                    $this->orderGoodsReturnManager->editGoodsReturn($data, $returnInfo);
                    if ($returnInfo->getReturnType() != 3 && $returnInfo->getRefundPayType() == 'balancePay' && $data['returnState'] == 2) {//余额退款
                        $currency       = Common::configValue($orderGoodsInfo['currencyCode'], 'currency');
                        $userInfo       = $this->entityManager->getRepository(User::class)->findOneBy(['userId' => $returnInfo->getUserId()]);
                        $returnAmount   = number_format($returnInfo->getReturnAmount()/$currency['rate'], 2, '.', '');
                        $userMoney      = $userInfo->getUserMoney() + $returnAmount;
                        $this->balanceLogManager->addBalanceLog([
                            'userId'    => $returnInfo->getUserId(),
                            'userName'  => $returnInfo->getUserName(),
                            'balanceChangeType' => 5,
                            'balanceChangeNum'  => $returnAmount,
                            'balanceChangedAmount' => $userMoney,
                            'balanceChangeTime' => time(),
                            'balanceChangeInfo' => $this->translator->translate('售后退款，订单编号：') . $returnInfo->getOrderSn()
                        ]);
                        $this->userManager->updateUserMoney($userMoney, $userInfo);
                    }
                    $this->entityManager->commit();
                    $this->adminCommon()->addOperLog($this->translator->translate('售后申请处理成功!'), $this->translator->translate('售后管理'));
                } catch (\Exception $e) {
                    $this->entityManager->rollback();
                    $this->flashMessenger()->addWarningMessage($this->translator->translate('售后申请处理失败!'));
                }
                return $this->redirect()->toRoute('sales-service', [], ['query' => $queryData]);
            }
        }

        return ['returnInfo' => $returnInfo, 'orderGoodsInfo' => $orderGoodsInfo, 'form' => $form, 'queryData' => $queryData];
    }

    /**
     * 查看退换货结果详情
     * @return array
     */
    public function viewAction()
    {
        $returnId = (int) $this->params()->fromRoute('id', -1);
        $returnInfo = $this->entityManager->getRepository(OrderGoodsReturn::class)->findOneBy(['returnId' => $returnId]);
        if ($returnInfo->getReturnState() == 1 || $returnInfo == null) return $this->adminCommon()->toReferer();

        $queryData = $this->params()->fromQuery();

        $orderGoodsInfo = $this->entityManager->getRepository(OrderGoods::class)->findOrderGoodsAndOrder($returnInfo->getOrderGoodsId());

        return ['returnInfo' => $returnInfo, 'orderGoodsInfo' => $orderGoodsInfo, 'queryData' => $queryData];
    }

    /**
     * 删除退换货信息
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $returnId = (int) $this->params()->fromRoute('id', -1);
        $returnInfo = $this->entityManager->getRepository(OrderGoodsReturn::class)->findOneBy(['returnId' => $returnId, 'returnState' => 1]);
        if ($returnInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该信息状态不允许删除!'));
            return $this->adminCommon()->toReferer();
        }

        $this->orderGoodsReturnManager->deleteGoodsReturn($returnInfo);

        $this->adminCommon()->addOperLog($this->translator->translate('退换货信息删除成功!'), $this->translator->translate('售后管理'));
        return $this->adminCommon()->toReferer();
    }
}